#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""docstring
models
"""
import os
import re
import json
from datetime import datetime

from flask import url_for
from werkzeug import cached_property
from sqlalchemy.ext.hybrid import hybrid_property
from flask.ext.sqlalchemy import BaseQuery
from planet.extensions import db, cache, photos


class PostQuery(BaseQuery):
    def jsonify(self):
        items = []
        for item in self.all():
            items.append(
                dict(id=item.id,
                     title=item.title,
                     created=datetime.strftime(item.created, "%Y-%m-%d")))
        return items


class Post(db.Model):
    query_class = PostQuery

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(140), index=True)
    _thumb = db.Column('thumb', db.String(40))
    body = db.Column(db.Text)
    status = db.Column(db.Integer, default=1)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    updated = db.Column(db.DateTime, default=datetime.utcnow,
                        onupdate=datetime.utcnow)

    __mapper_args__ = {'order_by': id.desc()}

    @cached_property
    def json(self):
        """
        Returns dict of safe attributes for passing into
        a JSON request.
        """
        return dict(id=self.id,
                    title=self.title,
                    body=self.body,
                    created=datetime.strftime(self.created, "%Y-%m-%d")
                    )

    def __init__(self, *args, **kwargs):
        super(Post, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.title

    @hybrid_property
    def thumb(self):
        if self._thumb:
            return photos.url(self._thumb)
        return None

    @thumb.setter
    def thumb(self, thumb):
        if thumb:
            self._thumb = thumb
